package com.idea.relax.log.support;

import com.idea.relax.log.logger.LogLevel;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @className: LoggerUtil
 * @description: 日志输出的工具类
 * @author: salad
 * @date: 2022/12/11
 **/
@Slf4j
public class LoggerUtil {

    private StringBuilder logText;

    private final List<Object> logArgs;

    private Throwable ex = null;

    private LoggerUtil() {
        this.logText = new StringBuilder();
        this.logArgs = new ArrayList<>();
    }

    public static LoggerUtil getLogger() {
        return new LoggerUtil();
    }

    public void addArgs(Object... args) {
        logArgs.addAll(Arrays.asList(args));
    }

    public void addLogText(String text) {
        logText.append(text);
    }

    public void addLog(String text, Object... args) {
        logText.append(text);
        logArgs.addAll(Arrays.asList(args));
    }

    public void setThrowable(Throwable ex){
        this.ex = ex;
    }

    public void log(LogLevel logLevel) {
        switch (logLevel) {
            case INFO:
                log.info(logText.toString(), logArgs.toArray());
                break;
            case WARN:
                log.warn(logText.toString(), logArgs.toArray());
                break;
            case ERROR: {
                if (ex != null) {
                    logArgs.add(ex);
                    log.error(logText.toString(), logArgs.toArray());
                } else {
                    log.error(logText.toString(), logArgs.toArray());
                }
            }
            break;
            default:
                log.debug(logText.toString(), logArgs.toArray());
                break;
        }
        clear();
    }

    public void clear() {
        this.logText = new StringBuilder();
        this.logArgs.clear();
        this.ex = null;
    }

}
